﻿/******************************************************************
 * 功能描述：提供对WebApi访问的一些公共函数
 * 创建时间：2013-07-10
 * 作者：Panxinming
 * 版本：1.0
 * 修订描述：
 * 最后修订日期：
 * Create: 2013-12-02 By Panxinming
 ******************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;


namespace EmoneyWeiXinCommon
{
    public class WebApiHelper
    {
        /// <summary>
        /// 按照OpenAPI规则生成对应URL，主要为原始URL增加签名
        /// </summary>
        /// <param name="sUrl"></param>
        /// <param name="md5Key"></param>
        /// <returns></returns>
        public static string CreateUrl(string sUrl, string md5Key)
        {
            Uri uri;
            if (!Uri.TryCreate(sUrl, UriKind.RelativeOrAbsolute, out uri))
            {
                return sUrl;
            }

            List<string> list = new List<string>();
            string queryStr = uri.Query;
            if (queryStr.IndexOf("?") == 0)
            {
                queryStr = queryStr.Substring(1);
            }
            string[] querys = queryStr.Split('&');
            foreach (string q in querys)
            {
                list.Add(q);
            }
            list.Sort();
            StringBuilder sBuilder = new StringBuilder();
            foreach (string q in list)
            {
                sBuilder.Append(q);
            }
            string toEncrypt = sBuilder.ToString() + md5Key;
            string md5New = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(toEncrypt, "md5");
            //LogManager.DefaultLogger.Info(toEncrypt + "==>" + md5New);
            return sUrl + "&encrypt=" + md5New;
        }

        /// <summary>
        /// 生成签名EncryptKey
        /// </summary>
        /// <param name="sUrl"></param>
        /// <param name="md5Key">encrypt</param>
        /// <returns></returns>
        public static string CreateEncryptKey(string sUrl, string md5Key)
        {
            Uri uri;
            if (!Uri.TryCreate(sUrl, UriKind.RelativeOrAbsolute, out uri))
            {
                return sUrl;
            }

            List<string> list = new List<string>();
            string queryStr = uri.Query;
            if (queryStr.IndexOf("?") == 0)
            {
                queryStr = queryStr.Substring(1);
            }
            string[] querys = queryStr.Split('&');
            foreach (string q in querys)
            {
                list.Add(q);
            }
            list.Sort();
            StringBuilder sBuilder = new StringBuilder();
            foreach (string q in list)
            {
                sBuilder.Append(q);
            }
            string toEncrypt = sBuilder.ToString() + md5Key;
            string md5New = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(toEncrypt, "md5");
            //LogManager.DefaultLogger.Info(toEncrypt + "==>" + md5New);
            return md5New;
        }

        public static string CreateMD5Key(string sUrl, params string[] args)
        {
            if (args == null || args.Length <= 0)
            {
                return sUrl;
            }
            StringBuilder sBuilder = new StringBuilder();
            foreach (object q in args)
            {
                sBuilder.Append(q);
            }

            string toEncrypt = sBuilder.ToString() + Config.WebApiEncryptKey;
            string md5New = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(toEncrypt, "md5");

            return sUrl + "&encrypt=" + md5New;
        }

        /// <summary>
        /// 以Get协议调用WebApi，默认utf-8协议
        /// </summary>
        /// <param name="baseUrl"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        private static string CallGetApi(string baseUrl, string query)
        {
            try
            {
                string apiUrl = CreateUrl(baseUrl + "?" + query, Config.WebApiEncryptKey);
                HttpWebRequest request = WebRequest.Create(apiUrl) as HttpWebRequest;
                request.Method = "GET";
                request.KeepAlive = false;
                request.ContentType = "application/json";
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                System.IO.Stream responseStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
                string srcString = reader.ReadToEnd();
                LogManager.DefaultLogger.Info("WebApiHelper=>CallGetApi [" + baseUrl + "] [" + query + "] [" + srcString + "]");
                return srcString;
            }
            catch (WebException wex)
            {
                LogManager.DefaultLogger.Error(wex, "WebApiHelper=>CallGetApi 发生WebException异常[" + wex.Message + "]： [" + baseUrl + "][" + query + "]");
                return wex.Message;
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, "WebApiHelper=>CallGetApi 发生Exception异常[" + ex.Message + "]： [" + baseUrl + "][" + query + "]");
                return ex.Message;
            }
        }

        /// <summary>
        /// 以Get协议调用WebApi，传入拼装好的ApiUrl
        /// </summary>
        /// <param name="url"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string CallGetApi(string url, Encoding encode)
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "GET";
                request.KeepAlive = false;
                request.ContentType = "application/json";
                request.Timeout = 3000;

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                System.IO.Stream responseStream = response.GetResponseStream();
                System.IO.StreamReader reader;
                reader = new System.IO.StreamReader(responseStream, encode);
                string srcString = reader.ReadToEnd();
                //LogManager.DefaultLogger.Info("WebApiHelper=>CallGetApi [" + url + "] [" + srcString + "]");
                return srcString;
            }
            catch (WebException wex)
            {
                LogManager.DefaultLogger.Error(wex, "WebApiHelper=>CallGetApi 发生WebException异常[" + wex.Message + "]： [" + url + "]");
                return wex.Message;
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, "WebApiHelper=>CallGetApi 发生Exception异常[" + ex.Message + "]： [" + url + "]");
                return ex.Message;
            }

        }

        /// <summary>
        /// 以Get协议调用WebApi，传入拼装好的ApiUrl，默认utf-8协议
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string CallGetApi(string url)
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "GET";
                request.KeepAlive = false;
                request.ContentType = "application/json";
                request.Timeout = 3000;

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                System.IO.Stream responseStream = response.GetResponseStream();
                System.IO.StreamReader reader;
                reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
                string srcString = reader.ReadToEnd();
                //MyTrace.get().add("WebApiHelper=>CallGetApi [" + url + "] [" + srcString + "]");
                return srcString;
            }
            catch (WebException wex)
            {
                MyTrace.get().add("WebApiHelper=>CallGetApi 发生WebException异常[" + wex.Message + "]： [" + url + "]");
                return wex.Message;
            }
            catch (Exception ex)
            {
                MyTrace.get().add("WebApiHelper=>CallGetApi 发生Exception异常[" + ex.Message + "]： [" + url + "]");
                return ex.Message;
            }

        }
        /// <summary>
        /// 获取Api的内容
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string getUrl(string url)
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "GET";
                request.KeepAlive = false;
                request.ContentType = "application/json";
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                System.IO.Stream responseStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
                string srcString = reader.ReadToEnd();
                return srcString;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
    }
}
